import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'utils/error_handler.dart';
import 'utils/app_routes.dart';
import 'utils/navigation_manager.dart';
import 'utils/performance_monitor.dart';
import 'examples/music_widgets_example.dart';
import 'examples/music_player_page_example.dart';
import 'examples/music_search_example.dart';
import 'examples/playlist_page_example.dart';
import 'examples/floating_player_example.dart';
import 'viewmodels/music_player_view_model.dart';
import 'viewmodels/music_search_view_model.dart';
import 'models/music_item_model.dart';
import 'pages/splash_page.dart';
import 'pages/permission_test_page.dart';
import 'pages/ios_permission_test_page.dart';
import 'services/floating_player_service.dart';
import 'services/audio_service_handler.dart';
import 'services/lockscreen_state_manager.dart';
import 'services/permission_manager.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();

  // 启动性能监控会话
  PerformanceMonitor.startMonitoringSession('MusicApp');

  // 设置权限回调
  PermissionManager.setPermissionCallbacks(
    onPermissionDenied: (message) {
      debugPrint('权限被拒绝: $message');
    },
    onPermissionGranted: (message) {
      debugPrint('权限授予成功: $message');
    },
  );

  runApp(const MusicApp());
}

class MusicApp extends StatelessWidget {
  const MusicApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MultiProvider(
      providers: [
        // 音乐播放器 ViewModel
        ChangeNotifierProvider(create: (_) => MusicPlayerViewModel()),
        // 音乐搜索 ViewModel
        ChangeNotifierProvider(create: (_) => MusicSearchViewModel()),
      ],
      child: MaterialApp(
        title: '音乐播放器',
        scaffoldMessengerKey: GlobalErrorHandler.scaffoldMessengerKey,
        navigatorObservers: [
          FloatingPlayerRouteObserver(),
          NavigationRouteObserver(),
        ],
        theme: ThemeData(
          colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
          useMaterial3: true,
        ),
        home: const SplashPage(),
        routes: AppRoutes.routes,
        onGenerateRoute: AppRoutes.onGenerateRoute,
      ),
    );
  }
}

class HomePage extends StatefulWidget {
  const HomePage({super.key});

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage>
    with FloatingPlayerPageMixin, NavigationMixin {
  /// 音频服务处理器
  late AudioServiceHandler _audioServiceHandler;

  /// 锁屏状态管理器
  late LockscreenStateManager _lockscreenStateManager;

  @override
  void initState() {
    super.initState();
    // 初始化服务
    WidgetsBinding.instance.addPostFrameCallback((_) {
      _initializeServices();
      FloatingPlayerService.initialize(context);
      initFloatingPlayer();
    });
  }

  /// 初始化音频服务和锁屏管理
  Future<void> _initializeServices() async {
    try {
      final musicPlayerViewModel =
          Provider.of<MusicPlayerViewModel>(context, listen: false);

      // 初始化音频服务处理器
      _audioServiceHandler = AudioServiceHandler.instance;
      await _audioServiceHandler.initialize(musicPlayerViewModel);

      // 初始化锁屏状态管理器
      _lockscreenStateManager = LockscreenStateManager.instance;
      await _lockscreenStateManager.initialize(
        musicPlayerViewModel: musicPlayerViewModel,
        audioServiceHandler: _audioServiceHandler,
      );

      debugPrint('音频服务和锁屏管理初始化完成');
    } catch (error) {
      debugPrint('初始化音频服务失败: $error');
    }
  }

  @override
  void dispose() {
    // 释放音频服务资源
    _audioServiceHandler.dispose();
    _lockscreenStateManager.dispose();

    disposeFloatingPlayer();
    super.dispose();
  }

  /// 测试后台播放和锁屏控制功能
  void _testBackgroundPlayback(BuildContext context) async {
    if (!mounted) return;

    final musicPlayerViewModel =
        Provider.of<MusicPlayerViewModel>(context, listen: false);

    // 检查权限
    final hasPermissions = await PermissionManager.instance.checkPermissions();
    if (!mounted) return;

    if (!hasPermissions) {
      final granted =
          await PermissionManager.instance.requestAudioPermissions();
      if (!mounted) return;

      if (!granted) {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(
            content: Text('需要通知权限才能使用锁屏控制功能'),
            duration: Duration(seconds: 3),
          ),
        );
        return;
      }
    }

    // 创建测试音乐数据
    const testMusic = MusicItemModel(
      id: 'background_test_001',
      title: '后台播放测试',
      artist: '测试艺术家',
      album: '测试专辑',
      albumArt:
          'https://y.gtimg.cn/music/photo_new/T002R300x300M000003rsKF44GyaSk.jpg',
      audioUrl: 'https://music.163.com/song/media/outer/url?id=553310243.mp3',
      duration: Duration(minutes: 4, seconds: 15),
      sourceType: 'test',
    );

    // 设置播放列表并开始播放
    musicPlayerViewModel.setPlaylist([testMusic]);
    await musicPlayerViewModel.play(testMusic);
    if (!mounted) return;

    // 显示悬浮播放器
    showFloatingPlayer();

    // 强制同步锁屏信息
    _lockscreenStateManager.forceSyncToLockscreen();

    ScaffoldMessenger.of(context).showSnackBar(
      const SnackBar(
        content: Text('后台播放已启动！请锁屏或切换到后台测试锁屏控制功能'),
        duration: Duration(seconds: 5),
      ),
    );
  }

  /// 测试悬浮播放器功能
  void _testFloatingPlayer(BuildContext context) {
    final musicPlayerViewModel =
        Provider.of<MusicPlayerViewModel>(context, listen: false);

    // 创建测试音乐数据
    const testMusic = MusicItemModel(
      id: 'test_001',
      title: '测试歌曲',
      artist: '测试艺术家',
      album: '测试专辑',
      albumArt:
          'https://y.gtimg.cn/music/photo_new/T002R300x300M000003rsKF44GyaSk.jpg',
      audioUrl: 'https://music.163.com/song/media/outer/url?id=553310243.mp3',
      duration: Duration(minutes: 3, seconds: 30),
      sourceType: 'test',
    );

    // 设置播放列表并开始播放
    musicPlayerViewModel.setPlaylist([testMusic]);
    musicPlayerViewModel.play(testMusic);

    // 显示悬浮播放器
    showFloatingPlayer();

    ScaffoldMessenger.of(context).showSnackBar(
      const SnackBar(
        content: Text('悬浮播放器已启动，可以导航到其他页面查看效果'),
        duration: Duration(seconds: 3),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: CustomScrollView(
        slivers: [
          // 自定义 AppBar
          SliverAppBar(
            expandedHeight: 200.0,
            floating: false,
            pinned: true,
            backgroundColor: Theme.of(context).primaryColor,
            flexibleSpace: FlexibleSpaceBar(
              title: const Text(
                '音乐播放器',
                style: TextStyle(
                  color: Colors.white,
                  fontWeight: FontWeight.bold,
                ),
              ),
              background: Container(
                decoration: BoxDecoration(
                  gradient: LinearGradient(
                    begin: Alignment.topCenter,
                    end: Alignment.bottomCenter,
                    colors: [
                      Theme.of(context).primaryColor,
                      Theme.of(context).primaryColor.withOpacity(0.8),
                    ],
                  ),
                ),
                child: const Center(
                  child: Icon(
                    Icons.music_note,
                    size: 80,
                    color: Colors.white54,
                  ),
                ),
              ),
            ),
          ),

          // 主要功能区域
          SliverToBoxAdapter(
            child: Padding(
              padding: const EdgeInsets.all(16.0),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  // 快速操作区域
                  _buildQuickActionsSection(context),
                  const SizedBox(height: 24),

                  // 当前播放状态
                  _buildCurrentPlayingSection(context),
                  const SizedBox(height: 24),

                  // 功能入口区域
                  _buildFunctionEntriesSection(context),
                  const SizedBox(height: 24),

                  // 示例和测试区域
                  _buildExamplesSection(context),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }

  /// 构建快速操作区域
  Widget _buildQuickActionsSection(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        const Text(
          '快速操作',
          style: TextStyle(
            fontSize: 20,
            fontWeight: FontWeight.bold,
          ),
        ),
        const SizedBox(height: 16),
        Row(
          children: [
            Expanded(
              child: _buildActionCard(
                context,
                icon: Icons.search,
                title: '搜索音乐',
                subtitle: '发现新音乐',
                onTap: () => NavigationManager.toMusicSearch(context),
              ),
            ),
            const SizedBox(width: 12),
            Expanded(
              child: _buildActionCard(
                context,
                icon: Icons.queue_music,
                title: '播放列表',
                subtitle: '管理音乐',
                onTap: () => NavigationManager.toPlaylist(context),
              ),
            ),
          ],
        ),
      ],
    );
  }

  /// 构建当前播放状态区域
  Widget _buildCurrentPlayingSection(BuildContext context) {
    return Consumer<MusicPlayerViewModel>(
      builder: (context, viewModel, child) {
        if (viewModel.currentTrack == null) {
          return Container(
            padding: const EdgeInsets.all(16),
            decoration: BoxDecoration(
              color: Colors.grey.shade100,
              borderRadius: BorderRadius.circular(12),
            ),
            child: const Row(
              children: [
                Icon(Icons.music_off, color: Colors.grey),
                SizedBox(width: 12),
                Text(
                  '暂无播放内容',
                  style: TextStyle(color: Colors.grey),
                ),
              ],
            ),
          );
        }

        return Container(
          padding: const EdgeInsets.all(16),
          decoration: BoxDecoration(
            gradient: LinearGradient(
              colors: [
                Theme.of(context).primaryColor.withOpacity(0.1),
                Theme.of(context).primaryColor.withOpacity(0.05),
              ],
            ),
            borderRadius: BorderRadius.circular(12),
            border: Border.all(
              color: Theme.of(context).primaryColor.withOpacity(0.3),
            ),
          ),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              const Text(
                '正在播放',
                style: TextStyle(
                  fontSize: 16,
                  fontWeight: FontWeight.bold,
                ),
              ),
              const SizedBox(height: 8),
              Row(
                children: [
                  // 专辑封面
                  Container(
                    width: 50,
                    height: 50,
                    decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(8),
                      color: Colors.grey.shade200,
                    ),
                    child: viewModel.currentTrack!.albumArt != null &&
                            viewModel.currentTrack!.albumArt!.isNotEmpty
                        ? ClipRRect(
                            borderRadius: BorderRadius.circular(8),
                            child: Image.network(
                              viewModel.currentTrack!.albumArt!,
                              fit: BoxFit.cover,
                              errorBuilder: (context, error, stackTrace) {
                                return const Icon(Icons.music_note,
                                    color: Colors.grey);
                              },
                            ),
                          )
                        : const Icon(Icons.music_note, color: Colors.grey),
                  ),
                  const SizedBox(width: 12),
                  // 歌曲信息
                  Expanded(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(
                          viewModel.currentTrack!.title,
                          style: const TextStyle(
                            fontWeight: FontWeight.bold,
                          ),
                          maxLines: 1,
                          overflow: TextOverflow.ellipsis,
                        ),
                        Text(
                          viewModel.currentTrack!.artist,
                          style: TextStyle(
                            color: Colors.grey.shade600,
                          ),
                          maxLines: 1,
                          overflow: TextOverflow.ellipsis,
                        ),
                      ],
                    ),
                  ),
                  // 播放按钮
                  ValueListenableBuilder<bool>(
                    valueListenable: viewModel.isPlaying,
                    builder: (context, isPlaying, child) {
                      return IconButton(
                        onPressed: viewModel.togglePlayPause,
                        icon: Icon(
                          isPlaying ? Icons.pause : Icons.play_arrow,
                          color: Theme.of(context).primaryColor,
                        ),
                      );
                    },
                  ),
                ],
              ),
              const SizedBox(height: 8),
              // 快速跳转到播放页面
              TextButton(
                onPressed: () => NavigationManager.toMusicPlayer(context),
                child: const Text('打开播放页面'),
              ),
            ],
          ),
        );
      },
    );
  }

  /// 构建功能入口区域
  Widget _buildFunctionEntriesSection(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        const Text(
          '主要功能',
          style: TextStyle(
            fontSize: 20,
            fontWeight: FontWeight.bold,
          ),
        ),
        const SizedBox(height: 16),
        GridView.count(
          shrinkWrap: true,
          physics: const NeverScrollableScrollPhysics(),
          crossAxisCount: 2,
          crossAxisSpacing: 12,
          mainAxisSpacing: 12,
          childAspectRatio: 1.5,
          children: [
            _buildFunctionCard(
              context,
              icon: Icons.search,
              title: '音乐搜索',
              description: '搜索并播放音乐',
              onTap: () => NavigationManager.toMusicSearch(context),
            ),
            _buildFunctionCard(
              context,
              icon: Icons.play_circle_filled,
              title: '音乐播放器',
              description: '控制音乐播放',
              onTap: () => NavigationManager.toMusicPlayer(context),
            ),
            _buildFunctionCard(
              context,
              icon: Icons.queue_music,
              title: '播放列表',
              description: '管理播放队列',
              onTap: () => NavigationManager.toPlaylist(context),
            ),
            _buildFunctionCard(
              context,
              icon: Icons.picture_in_picture,
              title: '悬浮播放器',
              description: '测试悬浮功能',
              onTap: () => _testFloatingPlayer(context),
            ),
          ],
        ),
      ],
    );
  }

  /// 构建示例区域
  Widget _buildExamplesSection(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        const Text(
          '示例和测试',
          style: TextStyle(
            fontSize: 20,
            fontWeight: FontWeight.bold,
          ),
        ),
        const SizedBox(height: 16),
        Wrap(
          spacing: 8,
          runSpacing: 8,
          children: [
            _buildExampleChip(
              context,
              label: 'UI 组件示例',
              onTap: () => Navigator.push(
                context,
                MaterialPageRoute(
                  builder: (context) => const MusicWidgetsExample(),
                ),
              ),
            ),
            _buildExampleChip(
              context,
              label: '播放页面示例',
              onTap: () => Navigator.push(
                context,
                MaterialPageRoute(
                  builder: (context) => const MusicPlayerPageExample(),
                ),
              ),
            ),
            _buildExampleChip(
              context,
              label: '搜索示例',
              onTap: () => Navigator.push(
                context,
                MaterialPageRoute(
                  builder: (context) => const MusicSearchExample(),
                ),
              ),
            ),
            _buildExampleChip(
              context,
              label: '播放列表示例',
              onTap: () => Navigator.push(
                context,
                MaterialPageRoute(
                  builder: (context) => const PlaylistPageExample(),
                ),
              ),
            ),
            _buildExampleChip(
              context,
              label: '悬浮播放器示例',
              onTap: () => Navigator.push(
                context,
                MaterialPageRoute(
                  builder: (context) => const FloatingPlayerExample(),
                ),
              ),
            ),
            _buildExampleChip(
              context,
              label: '后台播放测试',
              onTap: () => _testBackgroundPlayback(context),
            ),
            _buildExampleChip(
              context,
              label: '权限测试',
              onTap: () => Navigator.push(
                context,
                MaterialPageRoute(
                  builder: (context) => const PermissionTestPage(),
                ),
              ),
            ),
            _buildExampleChip(
              context,
              label: 'iOS 权限测试',
              onTap: () => Navigator.push(
                context,
                MaterialPageRoute(
                  builder: (context) => const IOSPermissionTestPage(),
                ),
              ),
            ),
          ],
        ),
      ],
    );
  }

  /// 构建操作卡片
  Widget _buildActionCard(
    BuildContext context, {
    required IconData icon,
    required String title,
    required String subtitle,
    required VoidCallback onTap,
  }) {
    return Card(
      elevation: 2,
      child: InkWell(
        onTap: onTap,
        borderRadius: BorderRadius.circular(12),
        child: Padding(
          padding: const EdgeInsets.all(16),
          child: Column(
            children: [
              Icon(
                icon,
                size: 32,
                color: Theme.of(context).primaryColor,
              ),
              const SizedBox(height: 8),
              Text(
                title,
                style: const TextStyle(
                  fontWeight: FontWeight.bold,
                ),
              ),
              Text(
                subtitle,
                style: TextStyle(
                  color: Colors.grey.shade600,
                  fontSize: 12,
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  /// 构建功能卡片
  Widget _buildFunctionCard(
    BuildContext context, {
    required IconData icon,
    required String title,
    required String description,
    required VoidCallback onTap,
  }) {
    return Card(
      elevation: 2,
      child: InkWell(
        onTap: onTap,
        borderRadius: BorderRadius.circular(12),
        child: Padding(
          padding: const EdgeInsets.all(16),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Icon(
                icon,
                size: 28,
                color: Theme.of(context).primaryColor,
              ),
              const SizedBox(height: 8),
              Text(
                title,
                style: const TextStyle(
                  fontWeight: FontWeight.bold,
                  fontSize: 14,
                ),
                textAlign: TextAlign.center,
              ),
              const SizedBox(height: 4),
              Text(
                description,
                style: TextStyle(
                  color: Colors.grey.shade600,
                  fontSize: 12,
                ),
                textAlign: TextAlign.center,
              ),
            ],
          ),
        ),
      ),
    );
  }

  /// 构建示例芯片
  Widget _buildExampleChip(
    BuildContext context, {
    required String label,
    required VoidCallback onTap,
  }) {
    return ActionChip(
      label: Text(label),
      onPressed: onTap,
      backgroundColor: Theme.of(context).primaryColor.withOpacity(0.1),
      labelStyle: TextStyle(
        color: Theme.of(context).primaryColor,
      ),
    );
  }
}
